#include "stdio.h"
#include "stdlib.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "unistd.h"
#include "linux/input.h"

int main(int argc, char *argv[]) 
{
    struct input_event in_ev;
    int x, y;
    int down;
    int valid;
    int fd;
    int len;

    if ( argc != 2 ) {
        fprintf(stderr, "usage:%d <input-dev>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if ( (fd = open(argv[1], O_RDONLY)) < 0 ) {
        perror("open error");
        exit(EXIT_FAILURE);
    }

    x = y = 0;
    down = -1;
    valid = 0;

    // len = sizeof(struct input_event);

    while (1) {
        if (read(fd, &in_ev, sizeof(struct input_event)) != sizeof(struct input_event)) {
            perror("read error");
            exit(EXIT_FAILURE);
        }
        
        switch (in_ev.type) {
            // 触摸事件
            case EV_KEY:
                if (in_ev.code == BTN_TOUCH) {
                    down = in_ev.value;
                    valid = 1;  // 有效按键
                }
                break;

            // 绝对位移事件
            case EV_ABS:
                switch (in_ev.code) {
                    case ABS_X:
                        x = in_ev.value;
                        valid = 1;
                        break;
                    case ABS_Y:
                        y = in_ev.value;
                        valid = 1;
                        break;
                }
                break;
            
            // 同步事件
            case EV_SYN:
                if (in_ev.type == SYN_REPORT) {
                    if (valid) {
                        switch (down) {
                            case 1:
                                printf("按下(%d, %d)\n", x, y);
                                break;
                            case 0:
                                printf("松开(%d, %d)\n", x, y);
                                break;
                            case -1:
                                printf("移动(%d, %d)\n", x, y);
                                break;
                        }

                        valid = 0;
                        down = -1;              
                    }
                }

                break;
        }
    }
    
}

